//
//  HomeTableViewController.swift
//  新浪微博
//
//  Created by 李国伟 on 15/12/6.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
import SVProgressHUD
let StatusNomal = "StatusNomal"
let Statusretweeted = "Statusretweeted"
let offset: CGFloat = 44
class HomeTableViewController: VisitorTableViewController {

    //设置数组模型
    private lazy var listViewModel = StatusVModelList()
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        if !UserAccountViewModel.shareModel.userlogin{
            visitorView?.setVisitorInfo(title: "关注一些人，回这里看看有什么惊喜", imageName: nil)
            return
        }
        
        //注册通知
       NSNotificationCenter.defaultCenter().addObserverForName(WBSelectedPictureNotification, object: nil, queue: nil) {[weak self] (n) -> Void in
        
        guard let urls =  n.userInfo![WBSelectedPictureURLs] as? [NSURL] else {
            return
        }
//            let urls = n.userInfo![WBSelectedPictureURLs] as? [NSURL]
        guard let indexPath = n.userInfo![WBSelectedPictureIndexPath] as? NSIndexPath else{
            return
        }
        
        guard let pictureView = n.object as? PhotoBrowserPresentDelegate else {
            return
        }
        
            let vc = PictureController(urls: urls, indexPath: indexPath)
        
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            vc.transitioningDelegate = self?.photoBrowserAnimator
            self?.photoBrowserAnimator.setDelegateParams(pictureView, dismissDelegate: vc, indexPath: indexPath )
            self?.presentViewController(vc, animated: true, completion: nil)
        }
        
        praperForView()
        loadDate()
    }
    
    //下拉刷新方法
    private func pullRefresh() {
        
        guard let count = listViewModel.refreshCount else {
            return
        }
        let height:CGFloat = 44
        self.refreshTipLabel.text = "刷新到\(count)条微博"
        self.refreshTipLabel.frame = CGRectMake(0, -2 * height, view.bounds.width, height)
//        self.refreshTipLabel.transform = CGRectOffset(rect, 0, - 2 * height)
        UIView.animateWithDuration(1.0, animations: { () -> Void in
               self.refreshTipLabel.frame.origin.y = height
            }) { (_) -> Void in
            UIView.animateWithDuration(2.0, animations: { () -> Void in
                self.refreshTipLabel.frame.origin.y = -2 * height
            })
        }
    }
    
    //下拉刷新提示label
    private lazy var refreshTipLabel: UILabel = {
        let label = UILabel(title: "", fontsize: 18,color: UIColor.whiteColor())
        label.backgroundColor = UIColor.orangeColor()
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return label
    }()
    
    //销毁通知
    deinit{
      
      NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func praperForView(){
        //注册两个可重用标识
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusNomal)
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: Statusretweeted)
        tableView.estimatedRowHeight = 300
        tableView.separatorStyle = .None
        tableView.tableFooterView = pullupView
        
        //设置刷新控制器,添加事件
        refreshControl = WBRefreshControl()
        refreshControl?.addTarget(self, action: "loadDate", forControlEvents: .ValueChanged)
        refreshControl?.tintColor = UIColor.clearColor()
        

    }
    
   var isLoading = false
   @objc private func loadDate(){
    
        //判断是否正在进行刷新
        isLoading = true
        //判断是否执行上拉刷新
        let ispullup = pullupView.isAnimating()
        refreshControl?.beginRefreshing()
        listViewModel.loadDates(ispullup: ispullup) { (isSuccess) -> () in
            
            //刷新完了之后结束刷新动画
           self.refreshControl?.endRefreshing()
           self.pullupView.stopAnimating()
            
            if isSuccess == false {
                SVProgressHUD.showInfoWithStatus("加载数据错误，请稍后再试")
                return
            }
            
           //刷新异步加载的数据
            self.tableView.reloadData()
            self.isLoading = false
            self.pullRefresh()
        }
    }
    
    //底部视图，设置下拉刷新指示器
    private var pullupView: UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        //必须要设置颜色
        indicator.color = UIColor.darkGrayColor()
        return indicator
    }()
}

//实现数据源方法
extension HomeTableViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusVModelList.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let viewModel = listViewModel.statusVModelList[indexPath.row] as? StatusViewModel

        let cell = tableView.dequeueReusableCellWithIdentifier((viewModel?.reusedIdntify)!, forIndexPath: indexPath) as! StatusCell
        
        //数据源方法中，设置底部视图，并启动动画
        if (indexPath.row == listViewModel.statusVModelList.count - 1) && !pullupView.isAnimating() {
            pullupView.startAnimating()
            loadDate()
        }
        
        cell.viewModel = viewModel
        return cell
    }
    
    /**
     行高
     
     -- 设置了预估行高
     * 当前显示的行高方法会调用三次（每个版本的Xcode调用次数可能不同）
     
     问题：预估行高如果不同，计算的次数不同！
     
     1. 使用预估行高，计算出预估的 contentSize
     2. 根据预估行高，判断计算次数，顺序计算每一行的行高，更新 contentSize
     3. 如果预估行高过大，超出预估范围，顺序计算后续行高，一直到填满屏幕退出，同时更新 contentSize
     4. 使用预估行高，每个 cell 的显示前需要计算，单个 cell 的效率是低的，从整体效率高！
     
     执行顺序 行数 -> 每个[cell -> 行高]
     
     预估行高：尽量靠近！
     
     -- 没设置了预估行高
     * 1. 计算所有行的高度
     * 2. 再计算显示行的高度
     
     执行顺序 行数 -> 行高 -> cell
     
     问题：为什么要调用所有行高方法？UITableView 继承自 UIScrollView
     表格视图滚动非常流畅 -> 需要提前计算出 contentSize
     
     苹果官方文档有指出，如果行高是固定值，就不要实现行高代理方法！
     
     实际开发中，行高一定要缓存！
     */
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let viewModel = listViewModel.statusVModelList[indexPath.row] as? StatusViewModel
        
        return viewModel?.rowHight ?? 0
    }
}
